package com.bclz.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerBIO implements Runnable {


    private Socket socket;

    public ServerBIO(Socket socket) {

        this.socket = socket;
    }

    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {

            System.out.println("Thread " + Thread.currentThread().getName() + " Connection Client....");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            String request, respose;
            //readline()方法会阻塞,等待客户端发送数据(该方法读取数据需要带有\s、\n回车或者换行,否者为空)
            while ((request = in.readLine()) != null) {
                System.out.println(Thread.currentThread().getName() + " From Client " + request);
                if (request.equals("end")) {
                    break;
                }
                out.println(Thread.currentThread().getName() + "Already Accept Message!!!!");
            }
            in.close();
            out.close();
        } catch (IOException e) {
            System.out.println("e = " + e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){

                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

    }

    public static void main(String[] args) {
        try {
            ExecutorService service = Executors.newCachedThreadPool();
            ServerSocket serverSocket = new ServerSocket(1919);
            int count = 0;
            while (true) {
                //accept()方法会阻塞,直到有客户端连接
                Socket socket = serverSocket.accept();
                service.execute(new Thread(new ServerBIO(socket), "Server" + count));
                count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }
}
